/**
 * 封装Http请求方法
 */

import type { AxiosRequestConfig, AxiosResponse } from 'axios'
import { request } from './request'
import type { ResponseData } from '@/shared/base'
import { Message } from '@arco-design/web-vue'
import { ResponseCode } from '@/shared/enum'
import { INIT_AUTH_HEADER } from '@/shared/constant'
import { getAuthHeader } from './auth'

const handlerResponse = <T>(
  resp: AxiosResponse<ResponseData<T>>,
  reslove: (value: ResponseData<T>) => void,
  reject: (reason?: any) => void
) => {
  const { data, status } = resp

  if (status === ResponseCode.SUCCESS_CODE) {
    const { code } = data
    if (code === ResponseCode.SUCCESS_CODE || code === ResponseCode.SUCCESS_CODE_V2) {
      reslove(data)
    } else if (code === ResponseCode.TOKEN_INVALID || code === ResponseCode.TOKEN_INVALID_V2) {
      Message.error({
        content: '登录失效，请重新登录',
        duration: 1000,
        onClose: () => {
          window.location.href = '/login'
        }
      })
    } else if (code === ResponseCode.SERVICE_CODE) {
      reject()
      Message.error(`${data?.msg || '请联系管理员处理'}`)
    } else {
      reject()
      Message.error(`服务异常：${data?.msg || '请联系管理员处理'}`)
    }
  } else {
    Message.error('服务调用异常')
    reject()
  }
}

export const authHeader = () => ({
  [INIT_AUTH_HEADER]: getAuthHeader()
})

const handlerRequestConfig = (payload?: AxiosRequestConfig) => {
  const headers = {
    ...authHeader(),
    ...payload?.headers
  }
  return {
    ...payload,
    headers
  }
}

export function DoGet<T>(url: string, payload?: AxiosRequestConfig) {
  return new Promise<ResponseData<T>>(async (reslove, reject) => {
    try {
      const resp = await request.get(url, handlerRequestConfig(payload))
      handlerResponse(resp, reslove, reject)
    } catch (e) {
      console.log(e, '请求失败')
      Message.error('服务调用异常')
      reject(e)
    }
  })
}

export function DoPost<T = any, K = any>(url: string, payload?: K, config?: AxiosRequestConfig) {
  return new Promise<ResponseData<T>>(async (reslove, reject) => {
    try {
      const resp = await request.post(url, payload, handlerRequestConfig(config))
      handlerResponse(resp, reslove, reject)
    } catch (e) {
      console.log(e, '请求失败')
      reject(e)
    }
  })
}

export function DoPut<T = any, K = any>(url: string, payload?: K, config?: AxiosRequestConfig) {
  return new Promise<ResponseData<T>>(async (reslove, reject) => {
    try {
      const resp = await request.put(url, payload, handlerRequestConfig(config))
      handlerResponse(resp, reslove, reject)
    } catch (e) {
      console.log(e, '请求失败')
      reject(e)
    }
  })
}

export function DoDelete<T = any>(url: string, config?: AxiosRequestConfig) {
  return new Promise<ResponseData<T>>(async (reslove, reject) => {
    try {
      const resp = await request.delete(url, handlerRequestConfig(config))
      handlerResponse(resp, reslove, reject)
    } catch (e) {
      console.log(e, '请求失败')
      reject(e)
    }
  })
}
